package ctrl;

import ctrl.action.ServletAction;
import ctrl.action.impl.CategoryServletAction;
import ctrl.action.impl.CheckoutServletAction;
import ctrl.action.impl.CatalogServletAction;
import ctrl.action.impl.ItemServletAction;
import ctrl.action.impl.LoginServletAction;
import ctrl.action.impl.LogoutServletAction;
import ctrl.action.impl.MgmtServletAction;
import ctrl.action.impl.SearchServletAction;
import ctrl.action.impl.ShoppingCartServletAction;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.ProjectConstants;

import model.Model;

/**
 * Servlet implementation class eFg4
 */
@WebServlet({"/efg4","/item","/category","/checkout","/shoppingcart","/login","/logout","/search","/mgmt"})
public class eFg4 extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private Map<String, ServletAction> actionMap = new HashMap<String, ServletAction>();
	
    @Override
	public void init() throws ServletException {
		super.init();
		ServletContext context = this.getServletContext();
		context.setAttribute(ProjectConstants.PARAMMODEL, new Model());
		actionMap.put(ProjectConstants.ACTIONEFG4, new CatalogServletAction(context));
		actionMap.put(ProjectConstants.ACTIONCATEGORY, new CategoryServletAction(context));
		actionMap.put(ProjectConstants.ACTIONITEM, new ItemServletAction(context));
		actionMap.put(ProjectConstants.ACTIONCHECKOUT, new CheckoutServletAction(context));
		actionMap.put(ProjectConstants.ACTIONSHOPPINGCART, new ShoppingCartServletAction(context));
		actionMap.put(ProjectConstants.ACTIONLOGIN, new LoginServletAction(context));
		actionMap.put(ProjectConstants.ACTIONLOGOUT, new LogoutServletAction(context));
		actionMap.put(ProjectConstants.ACTIONSEARCH, new SearchServletAction(context));
		actionMap.put(ProjectConstants.ACTIONMGMT, new MgmtServletAction(context));
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String servletPath = request.getServletPath();		
		ServletAction action = actionMap.get(servletPath);

		if(action != null){
			action.processRequest(request, response);
		}
		else{			
			System.out.println("URL error! Check the URL");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}

	@Override
	public void destroy() {
		super.destroy();
		actionMap = null;
	}
}
